// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PicknPlaceObjectGrip.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Manipulation.PicknPlace
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.PhysicalObjects;

    /// <summary>
    /// A base abstract implementation of IGripObject interface. Real objects derive from this base class
    /// </summary>
    public abstract class PicknPlaceObjectGrip : IPicknPlaceObjectGrip
    {
        /// <summary>
        ///  Initializes a new instance of the <see cref="PicknPlaceObjectGrip" /> class
        /// </summary>
        /// <param name="manpulatedObject">The object description</param>
        protected PicknPlaceObjectGrip(PhysicalObjectDescription manpulatedObject)
        {
            this.ManipulatedObjectDescription = manpulatedObject;
        }

        /// <summary>
        /// Gets the current element in the collection.
        /// </summary>
        public GripStyle Current
        {
            get
            {
                if (null != this.SupportedGripStyles)
                {
                    return this.SupportedGripStyles[this.CurrentEnumeratorIndex];
                }

                return (GripStyle)Enum.GetValues(typeof(GripStyle)).GetValue(this.CurrentEnumeratorIndex);
            }
        }

        /// <summary>
        /// Gets the non generic current collection member
        /// </summary>
        object IEnumerator.Current
        {
            get { return this.Current; }
        }

        /// <summary>
        /// Gets the description of the object
        /// </summary>
        public PhysicalObjectDescription ManipulatedObjectDescription { get; private set; }

        /// <summary>
        /// Gets or sets the index used for enumerating grip styles
        /// </summary>
        protected int CurrentEnumeratorIndex { get; set; }

        /// <summary>
        /// Gets or sets the supported list of grasp styles. If not explicitly set then the supported set
        /// is all grasp styles
        /// </summary>
        protected List<GripStyle> SupportedGripStyles { get; set; }

        /// <summary>
        /// Creates a Object Grip instance for a specific object
        /// </summary>
        /// <param name="objectDescription">Describes the object</param>
        /// <returns>Object Grip instance </returns>
        public static IPicknPlaceObjectGrip ObjectGripFactory(PhysicalObjectDescription objectDescription)
        {
            switch (objectDescription.Shape)
            {
                case PhysicalObjectShape.Cylinder:
                    return new PicknPlaceCylinderGrip(objectDescription);

                case PhysicalObjectShape.BoxRegular:
                    return new PicknPlaceBoxGrip(objectDescription);

                case PhysicalObjectShape.TopDownWithOrientation:
                    return new PicknPlaceTopDownWithOrientation(objectDescription);

                default:
                    throw new Exception(objectDescription.Shape.ToString() + " object type is not supported");
            }
        }

        /// <summary>
        /// Returns the palm plane 
        /// </summary>
        /// <param name="gripStyle">The grip style</param>
        /// <param name="objectPose">Object's pose</param>
        /// <returns>plane normal direction and distance from origin</returns>
        public abstract Vector4 GetPalmPlane(GripStyle gripStyle, Pose objectPose);

        /// <summary>
        /// Get the grip axis - the long axis orientation between grip fingers
        /// </summary>
        /// <param name="gripStyle">The grip style</param>
        /// <param name="objectPose">Object's pose</param>
        /// <returns>The grip axis</returns>
        public abstract Vector3 GetGripAxis(GripStyle gripStyle, Pose objectPose);

        /// <summary>
        /// Gets the centre point of the grip along the axis
        /// </summary>
        /// <param name="gripStyle">The grip style</param>
        /// <param name="objectPose">Object's pose</param>
        /// <returns>Center grip point</returns>
        public abstract Vector3 GetGripCenter(GripStyle gripStyle, Pose objectPose);

        /// <summary>
        /// Obtain a set of equivalent grip styles. Grip styles in an
        /// equivalent set can be pick or placed with out having to physically
        /// change grip. For example Grip from top or grip from bottom can be equivalent
        /// for a symmetric object
        /// </summary>
        /// <param name="gripStyle">Sample element for equivalent set</param>
        /// <returns>Set of equivalent grip styles</returns>
        public virtual IEnumerable<GripStyle> GetEquivalentGripStyleSet(GripStyle gripStyle)
        {
            return new GripStyle[] { gripStyle };
        }

        /// <summary>
        /// Gets an estimate of the position of the horizontal "table" surface from the object pose
        /// This is a temporary approach to obstacle (surface) avoidance. It will be replaced by 
        /// a more comprehensive obstacle avoidance
        /// </summary>
        /// <param name="objectPose">Object pose</param>
        /// <returns>Distance to the horizontal surface</returns>
        public abstract double GetHorizontalPlaneOffset(Pose objectPose);

        /// <summary>
        /// Gets a suggested gripper opening in M for the grip style
        /// </summary>
        /// <param name="gripStyle">grip style</param>
        /// <returns>Grip style</returns>
        public abstract double GetGripperOpeningInM(GripStyle gripStyle);

        /// <summary>
        /// Advances the  collection enumerator
        /// </summary>
        /// <returns>false if end of collection is reached</returns>
        public bool MoveNext()
        {
            ++this.CurrentEnumeratorIndex;
            if ((null != this.SupportedGripStyles && this.CurrentEnumeratorIndex >= this.SupportedGripStyles.Count) ||
                (this.CurrentEnumeratorIndex >= Enum.GetValues(typeof(GripStyle)).Length))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Sets the enumerator to the initial position before the first element in the collection
        /// </summary>
        public void Reset() 
        { 
            this.CurrentEnumeratorIndex = -1; 
        }

        /// <summary>
        /// Implement the IDisposable interface
        /// </summary>
        public void Dispose() 
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Returns an enumerator for the collection
        /// </summary>
        /// <returns>Enumerator for the collection</returns>
        public abstract IEnumerator<GripStyle> GetEnumerator();

        /// <summary>
        /// Returns the non generic enumerator for the collection
        /// </summary>
        /// <returns>Enumerator for the collection</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// <summary>
        /// Dispose of resources -- nothing to do
        /// </summary>
        /// <param name="disposing">Indicates whether or not Dispose() was called.</param>
        protected virtual void Dispose(bool disposing)
        {
        }

        /// <summary>
        /// Returns a plane, given the plane normal, and a point in the plane
        /// In other words just adds the distance from the origin
        /// </summary>
        /// <param name="normal">Plane normal</param>
        /// <param name="point">Point on the grip axis</param>
        /// <returns>Grip plane as {normal vector,  distance from Origin}</returns>
        protected Vector4 PlaneDistancefromOrigin(Vector3 normal, Vector3 point)
        {
            Vector4 plane = new Vector4(normal);
            plane.W = -Vector3.Dot(point, normal);
            return plane;
        }
    }
}
